<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
  <div th:replace="components/layout/header :: head(~{::title}, ~{}, ~{})">
    <title th:text="${vo.article.title  + ' - ' + global.siteInfo.websiteName}">
      专栏内容详情页 | 技术派
    </title>
  </div>

  <link rel="stylesheet" href="/css/views/column-detail.css" th:href="${global.siteInfo.oss + '/css/views/column-detail.css'}" />

  <body id="body">
    <!-- 导航栏 -->
    <div th:replace="components/layout/navbar :: navbar"></div>
    <div class="article-wrap">
        <!-- 目录 -->
        <div th:replace="views/column-detail/column-menu/index"></div>
        <!-- 内容 -->
        <div class="article-content-wrap bg-color">
          <!--  增加一个搜索的 Form 表单和左侧目录折叠的按钮  -->
          <div class="for-menu">
            <form class="bd-search d-flex align-items-center">
              <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
              <!-- 折叠目录按钮 -->
              <button class="btn bd-search-docs-toggle d-md-none pl-1 pr-0"
                      type="button"
                      data-toggle="collapse"
                      data-target="#collapseMenu"
                      aria-controls="collapseMenu"
                      aria-expanded="false"
                      aria-label="Toggle docs navigation">
                <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 30 30" role="img" focusable="false"><title>Menu</title><path stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="2" d="M4 7h22M4 15h22M4 23h22"/></svg>
              </button>
            </form>
          </div>

          <!--  正文 -->
          <div class="article-content-inter-wrap">
            <div th:replace="components/article/article-detail :: article_info(${vo.article}, null, ${vo.other}, ${vo.payUsers})"></div>
            <!--  评论  -->
            <div id="commentDiv">
              <div th:replace="components/comment/comment-list :: comment_list(${vo.hotComment}, ${vo.comments}, ${vo.article})"
              >
                评论列表
              </div>
            </div>
          </div>
          
          <!-- 文章内容导航 -->
          <div id="toc-container-position"></div>
          <div class="right-container toc-container column" style="display: none;">
            <div class="widget">
              <h3 class="com-nav-bar-title">目录</h3>
              <div id="contentMenu" class="toc"></div>
            </div>
          </div>

          <!--   文章分享   -->
          <div class="modal fade" id="shareModal" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title">分享文章</h5>
                  <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                  </button>
                </div>
                <div class="modal-body text-center">
                  <div class="qrcode-container mb-3">
                    <img id="shareQrCode" src="" alt="分享二维码">
                  </div>
                  <div class="short-url-container">
                    <div class="input-group" style="max-width: 500px; margin: 0 auto;">
                      <input type="text" id="shortUrl" class="form-control" readonly >
                      <div class="input-group-append">
                        <button class="btn btn-primary" type="button" onclick="copyAndClose()">复制</button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>
  </body>

  <script th:inline="javascript">
    // menu 是否显示
    function checkMediaQuery() {
      if (window.matchMedia('(min-width: 700px)').matches) {
        // 如果屏幕宽度大于600px，添加 'show' 类
        $('#collapseMenu').addClass('show');
      } else {
        // 否则，移除 'show' 类
        $('#collapseMenu').removeClass('show');
      }
    }

    // 监听窗口大小变化
    $(window).resize(checkMediaQuery);

    // 初始检查
    checkMediaQuery();

    // menu 滚动到指定位置
    function scrollToMenu() {
      const sectiona = $("a.active.section");
      if (sectiona.length > 0) {
        sectiona[0].scrollIntoView({
          behavior: "smooth",
          block: "center",
          inline: "center",
        });
      }
    }

    $('#collapseMenu').on('shown.bs.collapse', function () {
      scrollToMenu();
    })

    scrollToMenu();

    // 内容渲染
    const articleId = [[${ vo.article.articleId }]];

    // 跳转到评论的地方
    $("#commentFloatBtn").click(function () {
      document.getElementById("commentList").scrollIntoView(true);
    })

    // 点赞
    let praisedCount = [[${ vo.article.count.praiseCount }]]
    let praised = [[${ vo.article.praised }]]
    const isLogin = [[${ global.isLogin }]]
    const currentUserId = isLogin ? [[${ global.user != null ? global.user.userId : '' }]] : '';
    const currentUserAvatar = isLogin ? [[${ global.user != null ? global.user.photo : '' }]] : '';
    $("#praiseBtn").on('click', function () {
      if (!isLogin) {
        // 未登录，不执行相关操作
        return;
      }
      praised = !praised;
      praiseArticle(articleId, praised, function (data) {
        let avatarList = $('#praiseUsers')
        if (praised) {
          // 点赞
          praisedCount += 1;
          $("#praiseBtn").addClass("active")

          // 添加当前点赞用户的头像
          avatarList.prepend('' +
            '            <a class="g-user-popover approval-img" href="/user/' + currentUserId + '">\n' +
            '                <img src="' + currentUserAvatar + '">\n' +
            '            </a>')
        } else {
          // 取消点赞
          praisedCount -= 1;
          $("#praiseBtn").removeClass("active")

          // 移除当前点赞用户的头像
          let subItems = avatarList.children();
          for (let i = 0; i < subItems.length; i++) {
            let target = subItems[i];
            if (target.innerHTML.indexOf(currentUserAvatar) >= 0) {
              // 移除当前用户头像
              target.remove();
              break;
            }
          }
        }
        if (praisedCount > 0) {
          $('#praiseDesc').text(String(praisedCount) + '人已点赞');
        } else {
          $('#praiseDesc').text('真诚点赞，诚不我欺');
        }
      });
    });

    // 收藏
    let collectionCount = [[${ vo.article.count.collectionCount }]]
    let collected = [[${ vo.article.collected }]]
    $("#collectFloatBtn").click(function () {
      if (!isLogin) {
        // 未登录，不执行相关操作
        return;
      }

      collected = !collected;

      collectArticle(articleId, collected, function (data) {
        if (collected) {
          // 点赞
          collectionCount += 1;
          $("#collectFloatBtn").addClass("active")
        } else {
          collectionCount -= 1;
          $("#collectFloatBtn").removeClass("active")
        }

        if (collectionCount > 0) {
          $("#collectFloatBtn").addClass("with-badge")
          $('#collectFloatBtn').attr("badge", collectionCount)
        } else {
          $("#collectFloatBtn").removeClass("with-badge")
          $('#collectFloatBtn').removeAttr("badge")
        }
      });
    })

    // 二维码
    $("#qrIconTag").click(function () {
      const tag = $("#qrTipsTag")
      if (tag.hasClass("show")) {
        tag.removeClass("show")
      } else {
        tag.addClass("show")
      }
    })

    function bindCommentInputEvent() {
      // 直接评论
      const commentContent = $("#commentContent")
      const commentBtn = $("#commentBtn")
      commentBtn.click(function () {
        const content = commentContent.val()
        if (!content || content.length > 512) {
          toastr.error("评论内容长度要求在[1,512]之间")
          return
        }
        // 提交评论
        const params = {
          // 文章id
          articleId: articleId,
          // 评论内容
          commentContent: content,
        }
        post("/comment/api/post", params, function (data) {
          // 使用 Ajax 的方式，直接更新评论列表
          document.getElementById("commentDiv").innerHTML = data
          bindCommentInputEvent()
        })
      })

      // 直接评论监听
      $(document).on("input propertychange", "#commentContent", function () {
        const val = $(this).val()
        console.log(val)
        if (val) {
          $("#commentBtn").attr("disabled", false).removeClass("c-btn-disabled")
        } else {
          $("#commentBtn").attr("disabled", true).addClass("c-btn-disabled")
        }
      })
    }

    // 回复
    $(document).on("click", ".reply-comment", function () {
      const currentDom = $(this)
      createComment(currentDom)
    })

    // 回复编辑
    $(document).on("click", ".hf-pl", function () {
      const currentDom = $(this)
      commentSubmit(currentDom)
    })

    $(document).on("input propertychange", ".hf-input", function () {
      const currentDom = $(this)
      listenCommentBtn(currentDom)
    })

    // 点击回复创建评论
    const createComment = function (currentDom) {
      // 移除其他回复
      $(".hf-con").remove()

      // 获取回复人的名字
      var fhName = currentDom
        .parents(".common-item-content")
        .find(".comment-name")
        .html()
      //回复@
      var fhN = "回复@" + fhName + "："
      var fhHtml =
        '<div class="hf-con pull-left"><textarea class="hf-input" placeholder="" "></textarea><button disabled class="hf-pl hf-pl--disabled">评论</button></div>'
      if (currentDom.is(".hf-con-block")) {
        const currentWrap =
          (currentDom.parents(".comment-item-wrap").length &&
            currentDom.parents(".comment-item-wrap")) ||
          (currentDom.parents(".comment-item-wrap-second").length &&
            currentDom.parents(".comment-item-wrap-second"))

        currentWrap.find(".common-item-content").append(fhHtml)
        currentDom.removeClass("hf-con-block")
        //input框自动聚焦
        currentDom
          .parents(".common-item-content")
          .find(".hf-input")
          .val("")
          .focus()
          .attr("placeholder", fhN)
        // 取消回复
        currentDom.find(".reply-comment-text").hide()
        currentDom.find(".reply-comment-text-none").show()
      } else {
        currentDom.addClass("hf-con-block")
        currentDom.parents(".common-item-content").find(".pull-left").remove()
        // 回复
        currentDom.find(".reply-comment-text").show()
        currentDom.find(".reply-comment-text-none").hide()
      }
    }

    // 评论编辑&提交
    const commentSubmit = function (currentDom) {
      const replyContent = currentDom.siblings(".hf-input")
      const replyBtn = currentDom
        .parents(".common-item-content")
        .find(".reply-comment")

      if (!replyContent.val()) {
        toastr.error("回复内容不能为空")
        return
      }
      // 提交评论
      const params = {
        // 文章id
        articleId: $("#postsTitle").attr("data-id"),
        // 评论内容
        commentContent: replyContent.val(),
        // 回复的评论id
        parentCommentId: replyBtn.attr("data-reply-id"),
        // 回复的一级评论id
        topCommentId: replyBtn.attr("data-reply-top"),
      }
      post("/comment/api/post", params, function (data) {
        document.getElementById("commentDiv").innerHTML = data
        bindCommentInputEvent()
      })
    }

    // 监听按钮
    const listenCommentBtn = function (currentDom) {
      if (!currentDom.val()) {
        $(".hf-pl").attr("disabled", true).addClass("hf-pl--disabled")
      } else {
        $(".hf-pl").attr("disabled", false).removeClass("hf-pl--disabled")
      }
    }

    // 分组展开/收缩功能
    const initGroupToggle = function() {
      // 使用Map存储分组状态
      const groupStates = new Map();
      
      // 获取当前激活的文章所在分组
      const $activeSection = $('.section.active');
      const activeGroupName = $activeSection.attr('data-group');
      
      // 隐藏所有分组下的文章（除了当前激活文章所在的分组）
      $('.section[data-group]').each(function() {
        const $section = $(this);
        const groupName = $section.attr('data-group');
        
        if (groupName && groupName !== '未分组') {
          // 初始化分组状态
          // 如果是当前激活文章所在的分组，则默认展开（状态为true），否则默认收缩（状态为false）
          const isActiveGroup = (groupName === activeGroupName);
          groupStates.set(groupName, isActiveGroup);
          
          // 设置默认显示/隐藏状态
          if (!isActiveGroup) {
            $section.hide();
          }
        }
      });
      
      // 展开当前激活文章所在的分组（更新箭头状态）
      if (activeGroupName && activeGroupName !== '未分组') {
        $(`.group-header[data-group="${activeGroupName}"]`).find('.group-toggle').addClass('expanded');
      }
      
      // 为所有分组标题添加点击事件（使用事件委托提高性能）
      $(document).on('click', '.group-header', function() {
        const $header = $(this);
        const $toggle = $header.find('.group-toggle');
        const groupName = $header.attr('data-group');
        
        // 获取当前状态并取反
        const currentState = groupStates.get(groupName) || false;
        const newState = !currentState;
        
        // 更新状态和UI
        groupStates.set(groupName, newState);
        $toggle.toggleClass('expanded', newState);
        
        // 批量操作DOM，减少重排
        requestAnimationFrame(() => {
          $(`.section[data-group="${groupName}"]`).toggle(newState);
        });
      });
      
      // 初始状态设置 - 移除没有在当前激活分组中的其他分组的expanded类
      $('.group-header:not([data-group="' + activeGroupName + '"]) .group-toggle').removeClass('expanded');
    }

    // 更新浏览器标签页标题
    const updatePageTitle = function() {
      // 获取当前文章标题
      const currentArticleTitle = $('.section.active .title-text').text();
      // 获取专栏名称（通过查找专栏目录中任意文章的data-group属性，然后找到对应的分组标题）
      let columnName = '';
      const $groupHeader = $('.group-header').first();
      if ($groupHeader.length > 0) {
        columnName = $groupHeader.find('.group-name').text();
      }
      
      if (currentArticleTitle && columnName) {
        // 更新页面标题为"文章标题 - 专栏名称 - 网站名称"的格式
        document.title = currentArticleTitle + ' - ' + columnName + ' - ' + [[${global.siteInfo.websiteName}]];
      } else if (currentArticleTitle) {
        // 如果没有专栏名称，至少显示文章标题
        document.title = currentArticleTitle + ' - ' + [[${global.siteInfo.websiteName}]];
      }
    }

    // 生成内容导航菜单
    function generateTocMenu() {
      const tocContainer = $('.toc-container');
      if (tocContainer.length > 0) {
        const tocMenu = $('#contentMenu');
        // 获取文章内容中的所有标题，排除modal-dialog中的标题
        const contentHeadings = $('.article-info-wrap').find('h1, h2, h3, h4, h5, h6').not('.modal-dialog h1, .modal-dialog h2, .modal-dialog h3, .modal-dialog h4, .modal-dialog h5, .modal-dialog h6');

        if (contentHeadings.length > 0) {
          let tocHtml = '<ul class="markdown-toc-list">';
          let lastLevel = 0;

          contentHeadings.each(function() {
            const $heading = $(this);
            const level = parseInt(this.tagName.charAt(1));
            const text = $heading.text();
            const id = $heading.attr('id') || ('heading-' + text.replace(/\s+/g, '-').toLowerCase());

            // 为标题添加id属性
            $heading.attr('id', id);

            // 构建导航菜单HTML
            if (level > lastLevel) {
              tocHtml += '<ul>';
            } else if (level < lastLevel) {
              tocHtml += '</li></ul></li>';
            } else {
              tocHtml += '</li>';
            }

            // 添加不同级别的标题类名
            if (level === 2) {
              tocHtml += `<li><a class="toc-level-${level} toc-h2" href="#${id}" level="${level}">${text}</a>`;
            } else if (level === 3) {
              tocHtml += `<li><a class="toc-level-${level} toc-h3" href="#${id}" level="${level}">${text}</a>`;
            } else {
              tocHtml += `<li><a class="toc-level-${level}" href="#${id}" level="${level}">${text}</a>`;
            }
            lastLevel = level;
          });

          tocHtml += '</li></ul>';
          tocMenu.html(tocHtml);
          tocContainer.show();
          
          // 添加点击事件监听器以更新选中状态
          bindTocScrollSpy();
        } else {
          tocContainer.hide();
        }
      }
    }
    
    // 绑定滚动监听和点击事件以更新目录选中状态
    function bindTocScrollSpy() {
      // 为目录链接添加点击事件
      $('#contentMenu a').on('click', function(e) {
        e.preventDefault();
        // 移除所有现有选中状态
        $('#contentMenu a').removeClass('active');
        // 为当前点击的链接添加选中状态
        $(this).addClass('active');

        // 滚动到对应的内容区域
        const targetId = $(this).attr('href').substring(1);
        const targetElement = document.getElementById(targetId);
        if (targetElement) {
          targetElement.scrollIntoView({ behavior: 'smooth' });
        }
      });

      // 监听窗口滚动事件以自动更新选中状态
      $(window).on('scroll', function() {
        updateTocActiveState();
      });

      // 初始化时更新一次选中状态
      updateTocActiveState();
    }
    
    // 更新目录的活动状态
    function updateTocActiveState() {
      const scrollPosition = $(window).scrollTop() + 100; // 添加偏移量以更准确匹配

      // 移除所有现有选中状态
      $('#contentMenu a').removeClass('active');

      // 查找当前视口中的标题
      let currentHeadingId = '';
      $('.article-info-wrap :header[id]').each(function() {
        const headingTop = $(this).offset().top;
        if (headingTop <= scrollPosition) {
          currentHeadingId = $(this).attr('id');
        }
      });

      // 为对应的目录项添加选中状态
      if (currentHeadingId) {
        $('#contentMenu a[href="#' + currentHeadingId + '"]').addClass('active');
      }

      // 更新目录容器滚动位置
      const tocContainer = $('.toc-container');
      const activeLink = $('#contentMenu a.active');
      if (activeLink.length > 0) {
        const activeLinkTop = activeLink.offset().top - tocContainer.offset().top + tocContainer.scrollTop();
        tocContainer.scrollTop(activeLinkTop - tocContainer.height() / 2);
      }
    }

    $(document).ready(function () {

      // 生成内容导航菜单
      generateTocMenu();
    });

    bindCommentInputEvent()
    initGroupToggle()

    function copyAndClose() {
      // 复制短链
      copyShortUrl();
      // // 关闭弹窗，有个问题，关闭之后无法再次打开；先不关闭
      // $('#shareModal').hide();
    }
  </script>
</html>
